import {renderAsync} from 'docx-preview'
import jsPreviewExcel from '@js-preview/excel'
import '@js-preview/excel/lib/index.css'

export const previewDocx = async (blob: Blob, domId: string) => {
    const dom = document.getElementById(domId) as HTMLElement
    await renderAsync(blob, dom, dom, {
        className: "docx", //class name/prefix for default and document style classes
        inWrapper: true, //enables rendering of wrapper around document content
        hideWrapperOnPrint: false, //disable wrapper styles on print
        ignoreWidth: false, //disables rendering width of page
        ignoreHeight: false, //disables rendering height of page
        ignoreFonts: false, //disables fonts rendering
        breakPages: true, //enables page breaking on page breaks
        ignoreLastRenderedPageBreak: true, //disables page breaking on lastRenderedPageBreak elements
        experimental: false, //enables experimental features (tab stops calculation)
        trimXmlDeclaration: true, //if true, xml declaration will be removed from xml documents before parsing
        useBase64URL: false, //if true, images, fonts, etc. will be converted to base 64 URL, otherwise URL.createObjectURL is used
        renderChanges: false, //enables experimental rendering of document changes (inserions/deletions)
        renderHeaders: true, //enables headers rendering
        renderFooters: true, //enables footers rendering
        renderFootnotes: true, //enables footnotes rendering
        renderEndnotes: true, //enables endnotes rendering
        renderComments: false, //enables experimental comments rendering
        renderAltChunks: true, //enables altChunks (html parts) rendering
        debug: false, //enables additional logging
    })
}


export const previewXlsx = (domId: string, blob: Blob) => {
    const dom = document.getElementById(domId) as HTMLElement
    jsPreviewExcel.init(dom).preview(blob)
}

export const fileToBlob = (file: File) => {
    return new Promise((resolve) => {
        const reader = new FileReader()
        reader.readAsArrayBuffer(file)
        let blob = null
        reader.onload = (e: ProgressEvent<FileReader>) => {
            if(typeof e.target?.result === 'object') {
                blob = new Blob([e.target.result as BlobPart])
            } else {
                blob = e.target?.result
            }
            resolve(blob)
        }
    })
}